import datetime
# 李豪添加注释
# 添加注释测试
class BillManagementSystem:
    def __init__(self):
        self.income_records = []  # 存储收入记录
        self.expense_records = []  # 存储支出记录
        self.budget_limit = 0  # 月度预算限额
        self.current_month = datetime.datetime.now().month

    def run(self):
        while True:
            self.show_menu()
            choice = input("请输入选项序号：").strip()
            if choice == "1":
                self.record_income()
            elif choice == "2":
                self.record_expense()
            elif choice == "3":
                self.display_all_records()
            elif choice == "4":
                self.query_records()
            elif choice == "5":
                self.set_budget()
            elif choice == "6":
                self.monthly_statistics()
            elif choice == "7":
                print("感谢使用个人账单管理系统，期待您的下次使用！")
                break
            else:
                print("无效选项，请重新选择！")

    def show_menu(self):
        print("=" * 33)
        print("欢迎使用个人账单管理系统")
        print("=" * 33)
        print("请选择操作：")
        print("1. 记录收入")
        print("2. 记录支出")
        print("3. 查看所有账单")
        print("4. 查询账单")
        print("5. 设置月度预算")
        print("6. 查看月度统计报告")
        print("7. 退出系统")
        print("=" * 33)

    def record_income(self):
        print("请输入收入信息：")
        date, amount, category, note = self.get_record_input("收入")
        if amount > 0:
            self.income_records.append({"date": date, "amount": amount, "category": category, "note": note})
            print("收入已成功记录！")
        else:
            print("金额必须为正数！")

    def record_expense(self):
        print("请输入支出信息：")
        date, amount, category, note = self.get_record_input("支出")
        if amount > 0:
            self.expense_records.append({"date": date, "amount": amount, "category": category, "note": note})
            print("支出已成功记录！")
        else:
            print("金额必须为正数！")

    # 查看所有账单
    def display_all_records(self):
        print("\n收入记录：")
        self.display_records(self.income_records)
        print("\n支出记录：")
        self.display_records(self.expense_records)

    def query_records(self):
        print("查询账单：")
        query_type = input("按1日期、2日期范围、3类别查询，请输入序号：").strip()
        if query_type == "1":
            date = input("请输入日期（YYYY-MM-DD）：").strip()
            self.display_query_results(self.filter_records_by_date(date))
        elif query_type == "2":
            start_date = input("请输入起始日期（YYYY-MM-DD）：").strip()
            end_date = input("请输入结束日期（YYYY-MM-DD）：").strip()
            self.display_query_results(self.filter_records_by_date_range(start_date, end_date))
        elif query_type == "3":
            category = input("请输入类别：").strip()
            self.display_query_results(self.filter_records_by_category(category))
        else:
            print("无效查询类型！")

    def set_budget(self):
        try:
            self.budget_limit = float(input("请输入每月支出的预算限额："))
            print(f"预算已设置为 {self.budget_limit} 元")
        except ValueError:
            print("输入错误，请输入一个数字！")

    def monthly_statistics(self):
        income_total = self.calculate_monthly_total(self.income_records)
        expense_total = self.calculate_monthly_total(self.expense_records)
        remaining_budget = self.budget_limit - expense_total if self.budget_limit else "未设置"
        print("\n本月统计报告：")
        print(f"总收入：{income_total} 元")
        print(f"总支出：{expense_total} 元")
        print(f"剩余预算：{remaining_budget} 元")
        self.category_statistics()

    def get_record_input(self, record_type):
        try:
            date = input(f"日期（YYYY-MM-DD）：").strip()
            datetime.datetime.strptime(date, "%Y-%m-%d")  # 验证日期格式
            amount = float(input("金额："))
            category = input(f"类别（如工资、餐饮等）：").strip()
            note = input("备注：").strip()
            return date, amount, category, note
        except ValueError:
            print("输入格式错误，请重试！")
            return self.get_record_input(record_type)

    def display_records(self, records):
        if records:
            for record in records:
                print(f"日期：{record['date']}，金额：{record['amount']}，类别：{record['category']}，备注：{record['note']}")
        else:
            print("暂无记录！")

    def display_query_results(self, records):
        print("\n查询结果：")
        print("\n收入记录：")
        self.display_records([rec for rec in records if rec in self.income_records])
        print("\n支出记录：")
        self.display_records([rec for rec in records if rec in self.expense_records])

    def filter_records_by_date(self, date):
        return [rec for rec in self.income_records + self.expense_records if rec["date"] == date]

    def filter_records_by_date_range(self, start_date, end_date):
        return [rec for rec in self.income_records + self.expense_records if start_date <= rec["date"] <= end_date]

    def filter_records_by_category(self, category):
        return [rec for rec in self.income_records + self.expense_records if rec["category"] == category]

    def calculate_monthly_total(self, records):
        current_month = datetime.datetime.now().strftime("%Y-%m")
        return sum(rec["amount"] for rec in records if rec["date"].startswith(current_month))

    def category_statistics(self):
        categories = {}
        for record in self.expense_records:
            if record["category"] not in categories:
                categories[record["category"]] = 0
            categories[record["category"]] += record["amount"]
        print("\n各类别支出：")
        for category, total in categories.items():
            print(f"{category}：{total} 元")


# 启动系统
if __name__ == "__main__":
    system = BillManagementSystem()
    system.run()
